package com.itcast.yygh.msm.controller;

import com.itcast.common.result.R;
import com.itcast.common.utils.RandomUtil;
import com.itcast.yygh.msm.service.MsmService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/msm")
@RequiredArgsConstructor
public class MsmController {

    private final MsmService msmService;

    private final RedisTemplate<String, String> redisTemplate;

    @GetMapping(value = "/send/{phone}")
    public R code(@PathVariable String phone) {
        //1.根据手机号查询redis，如果查询到code验证码就直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) return R.ok();
        //2.如果redis没有查到code验证码，通过RandomUtil生成随机的验证码
        code = RandomUtil.getFourBitRandom();
        Map<String, Object> param = new HashMap<>();
        param.put("code", code);
        System.out.println("手机号为 " + phone + " 的验证码为: " + code);
        //3.进行短信的发送，返回一个状态 发送成功返回true，发送失败返回false
        boolean isSend = msmService.send(phone, "SMS_180051135", param);
        //4.判断发送的状态为true
        if (isSend) {
            //把验证码放在redis中
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            //5.发送失败
            return R.error().message("发送短信失败");
        }
    }
}